package com.wnxy.f_confirm;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class ConfirmConsumer {

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "queue-confirm",arguments = {
                    @Argument(name = "x-dead-letter-exchange",value = "exchange-dlx"),
                    @Argument(name = "x-dead-letter-routing-key",value = "dlx.xxx"),
                    @Argument(name = "x-message-ttl",value = "10000",type = "java.lang.Long"),
                    @Argument(name = "x-max-length",value = "2",type = "java.lang.Long"),
            }),
            exchange = @Exchange(name = "exchange-confirm",type = ExchangeTypes.TOPIC),
            key = "confirm.*"
    ))
    public void handlerMsg(String msg, Channel channel, Message message) throws IOException {
        try {
            int i = 1/0;
            System.out.println("消费者确认消息："+msg);
            // 消息手动确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
        } catch (Exception e) {
            e.printStackTrace();
            // 需求：消息消费失败，将消息重新投递到队列中；再次消费，消费还是消费失败，就可以拒绝消息
            // 消息是否重投过
            Boolean redelivered = message.getMessageProperties().getRedelivered();
            if (redelivered) {
                // 消息已经重投过
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
                System.out.println("重投的消息消费失败，已经拒绝！消息会丢失");
            } else {
                // 消息没有重投过，进行重投
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),true,true);
                System.out.println("消息已经重投：");
            }
        }
    }
}
